<template>
  <div class="companyManaIndex">
   <userHeader />
    <div class="breadClum">
      <span>
          <router-link :to="{path:'/pageIndex'}">  <a class="bread1">当前位置：首页  >  </a></router-link>
          <router-link :to="{path:'/systemSetting'}"> <a class="bread2">系统设置  ></a></router-link>
          <a class="bread2">企业管理</a>
      </span>
    </div>
    <div class="navList">
      <span class="sp1" @click.stop="addCompany">添加公司</span>
          <!--<span  @click.stop="editorTop">-->
               <!--编辑-->
          <!--</span>-->
        <!--<span @click.stop="deleteTop">-->
             <!--删除-->
        <!--</span>-->
    </div>
    <el-table
      :row-class-name="tableRowClassName"
      :row-style="showRow"
      :cell-class-name="cell"
      ref="tableData3"
      stripe=""
     :data="tableData3"
      @selection-change="handleSelectionChange"
      :height="height"
     style="width: 100%">
      <el-table-column
        width="70"
        prop="is_opera"

      >
        <template slot-scope="scope">
          <el-checkbox :disabled="scope.row.is_opera==0" ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
        prop="company_num"
        label="公司编号"
      >
      </el-table-column>
      <el-table-column label="公司名称">
        <el-table-column
          prop="first_process"
          label="一级分类"
          width="170">
          <template slot-scope="scope" >
            <span @click.stop="toggleExpanded(scope.$index)"  v-if=scope.row.first_process.is_show>
                    <img src="../../static/images/add.png"  v-if="!scope.row._expanded&&iconShow(scope.$index,scope.row)">
                    <img src="../../static/images/reduce.png" alt="" v-else>
                {{scope.row.first_process.company_name}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="second_process"
          label="二级分类"
          width="170">
          <template slot-scope="scope">
            <span @click.stop="toggleExpanded(scope.$index)"  v-if=scope.row.second_process.is_show>
                    <img src="../../static/images/add.png"  v-if="!scope.row._expanded&&iconShow(scope.$index,scope.row)">
                    <img src="../../static/images/reduce.png" alt="" v-else>
                {{scope.row.second_process.company_name}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="third_process"
          label="三级分类"
          width="170">
          <template slot-scope="scope">
           <span @click.stop="toggleExpanded(scope.$index)"  v-if=scope.row.third_process.is_show>
                    <img src="../../static/images/add.png"  v-if="!scope.row._expanded&&iconShow(scope.$index,scope.row)">
                    <img src="../../static/images/reduce.png" alt="" v-else>
                {{scope.row.third_process.company_name}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="fourth_process"
          label="四级分类"
          width="170">
          <template slot-scope="scope">
           <span @click.stop="toggleExpanded(scope.$index)"  v-if=scope.row.fourth_process.is_show>
                    <img src="../../static/images/add.png"  v-if="!scope.row._expanded&&iconShow(scope.$index,scope.row)">
                    <img src="../../static/images/reduce.png" alt="" v-else>
                {{scope.row.fourth_process.company_name}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="fifth_process"
          label="五级分类"
          width="170">
          <template slot-scope="scope">
             <span @click.stop="toggleExpanded(scope.$index)"  v-if=scope.row.fifth_process.is_show>
                    <img src="../../static/images/add.png"  v-if="!scope.row._expanded&&iconShow(scope.$index,scope.row)">
                    <img src="../../static/images/reduce.png" alt="" v-else>
                {{scope.row.fifth_process.company_name}}
            </span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column
        prop="company_level"
        label="级别"
        width="85">
      </el-table-column>
      <el-table-column
        prop="current_time"
        label="当前期间"
        width="135">
        <template slot-scope="scope">
          <span>{{editorStart_time(scope.row.current_time)}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="company_state"
        label="账号状态"
        width="125">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.company_state==1"
            active-color="#efba12"
            inactive-color="#dddddd">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        >
        <template slot-scope="scope">
          <span @click.stop="editor(scope.row.company_id,scope.row.company_pid,scope.row.index)" class="e-ditor">编辑</span>
          <span @click.stop="delete1(scope.row.company_id,scope.row.company_pid,scope.row.index)" class="d-elete">删除</span>
        </template>
      </el-table-column>
    </el-table>
    <!--添加企业弹出框-->
    <el-dialog :title=title :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :model="form" :rules="rules"  ref="editorForm">
        <el-form-item label="单位名称" :label-width="formLabelWidth" prop="company_name">
          <el-input v-model="form.company_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位编号" :label-width="formLabelWidth" prop="company_num">
          <el-input v-model="form.company_num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="company_sort" class="removeSort">
          <el-input v-model="company_sort" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上级企业" :label-width="formLabelWidth" prop="company_pid"  v-if="showTree">
          <el-tree
            empty-text="当前暂无公司数据请先手动添加"
            v-loading="loading"
            :data="data3"
            :props="defaultProps"
            :show-checkbox="true"
            default-expand-all
            :check-on-click-node="true"
            node-key="company_id"
            ref="tree"
            @check="checkTest"
            @check-change="setCheckedKeys"
            @node-click="nodeClick"
            :expand-on-click-node="false"
            :check-strictly=true
            highlight-current
            @current-change="changeCurrent">
          </el-tree>
        </el-form-item>
        <el-form-item label="账号状态" :label-width="formLabelWidth" prop="company_state">
          <el-radio v-model="form.company_state" label="1">在用</el-radio>
          <el-radio v-model="form.company_state" label="0">停用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEditor">取 消</el-button>
        <el-button type="primary" @click="confirmEditor('editorForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--<fixed />-->
    <deleteAlarm @cancelOpt="cancelOpt" @confirmOpt="confirmOpt" :dialogVisible2="dialogFormVisible2"/>
  </div>
</template>

<script>
  import userHeader from '@/components/header.vue'
//  import fixed from '@/components/fixed.vue'
  import deleteAlarm from '@/components/deleteAlarm.vue'
  import treeToArray from '@/page/test/index.js'
  import {strToHexCharCode,toFixedBit,dec2hex,formatTime,getNewDate,formatDateTime,formatDateYear } from  '@/utils/index.js';
  import {mapState} from 'vuex'
  export default({
    computed:{
      ...mapState({
        company_ids:state =>state.app.loginState.company_id||sessionStorage.getItem('company_id'),
        company_pids:state =>state.app.loginState.company_pid||sessionStorage.getItem('company_pid'),
        height:state=>sessionStorage.getItem('height')||state.app.height,
      }),
      editorStart_time(){
        return function (selectTypeArray) {
          return formatDateYear(selectTypeArray)
        }
      }
    },
    components:{
      deleteAlarm,
      userHeader
    },
    data (){
      var checkCompany = (rule, value, callback) => {
        if(this.$refs.tree.getCheckedNodes().length==0){
          return callback(new Error('请选择评价单位'));
        }else{
          callback()
        }
      };
      var checkCompanyName = (rule, value, callback) => {
        if(value==''||value==undefined){
          return callback(new Error('请输入单位名称'));
        }else{
          callback()
        }
      };
      var checkCompanyNum = (rule, value, callback) => {
        if(value==''||value==undefined){
          return callback(new Error('请输入单位编号'));
        }else{
          callback()
        }
      };
      var checkCompanyState = (rule, value, callback) => {
        if(value==''||value==undefined){
          return callback(new Error('请选择账号状态'));
        }else{
          callback()
        }
      };
      var checkSort=(rule, value, callback) => {
        var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/;
        if(this.company_sort!=undefined&&this.company_sort!=''){
          if(!re.test(this.company_sort)){
            return callback(new Error('请输入正确的排序数字'));
          }else{
            callback()
          }
        }else{
          callback()
        }
      };
      return {
        showTree:true,
        multipleSelection:[],
        accountStatus:1,
        dialogFormVisible2:false,
        formLabelWidth:'160px',
        dialogFormVisible:false,
        loading:true,
        title:'添加公司',
        self_identify:'',
        company_sort:'',
        expandAll: {
          type: Boolean,
          default: true
        },
        form:{},
        index:0,
        company_id:'',
        company_pid:'',
        data3:[],
        defaultProps: {
          children: 'son_company',
          label: 'company_name'
        },
        tableData3: [],
        rules: {
          company_pid:[
            { required: true,validator:checkCompany,trigger: 'blur'}
          ],
          company_name:[
            { required: true,validator:checkCompanyName,trigger: 'blur'}
          ],
          company_num:[
            { required: true,validator:checkCompanyNum,trigger: 'blur'}
          ],
          company_state:[
            { required: true,validator:checkCompanyState,trigger: 'blur'}
          ],
          company_sort:[
            { required: true,validator:checkSort,trigger: 'blur'}
          ]
        },
      }
    },
    methods: {
      cell({row, column, rowIndex, columnIndex}) {
        //第八列添加 red 类
        if(columnIndex==3||columnIndex==4 ||columnIndex==5||columnIndex==6||columnIndex==2){
          return "e-table-align-left"
        }

      },
      handleClose(){
        this.dialogFormVisible=false;
        this.$refs.tableData3.clearSelection()
        this.form={};
        this.showTree =true;
        if(this.$refs.tree){
          this.$refs.tree.setCheckedNodes([]);

        };
        ;
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      tableRowClassName ({row, rowIndex}) {
        //把每一行的索引放进row
        row.index = rowIndex;
      },
      checkTest(data,checkNode){

      },
      //树状结构分类
      changeCurrent(data,node,test){

      },
      nodeClick(data,checked,node){
        console.log(123)
        this.checkedId = data.company_id
        this.$refs.tree.setCheckedNodes([data]);
      },
      setCheckedKeys(data,checked,node){
        if(checked == true){
          this.checkedId = data.company_id;
          this.$refs.tree.setCheckedNodes([data]);
        }
      },
      showRow: function(row) {
        const show = (row.row.parent ? (row.row.parent._expanded && row.row.parent._show) : true)
        row.row._show = show
        return show ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;' : 'display:none;'
      },
      // 切换下级是否展开
      toggleExpanded: function(trIndex) {
        const record = this.tableData3[trIndex]
        record._expanded = !record._expanded
      },
      // 图标显示
      iconShow(index, record) {
        console.log(index,record)
        return ( record.son_company && record.son_company.length > 0)
      },
      addCompany(){
        this.dialogFormVisible =true
        this.title='添加公司'
        this.initCompanyData2();
        this.form.company_state ="1";
      },

      //导航下方删除按钮
      editorTop(){
        if(this.multipleSelection.length==0){
            this.$alert('请选择需要编辑的企业','提示')
          this.$refs.tableData3.clearSelection();
        }else if(this.multipleSelection.length>1){
          this.$alert('一次只能编辑一条数据','提示')
          this.$refs.tableData3.clearSelection();
        }else {
            this.editor(this.multipleSelection[0].company_id,
              this.multipleSelection[0].company_pid,
              this.multipleSelection[0].index)
        }
      },
      deleteTop(){
        if(this.multipleSelection.length==0){
          this.$alert('请选择需要删除的企业','提示')
          this.$refs.tableData3.clearSelection();
        }else {
            if(this.multipleSelection.length==1){
              this.delete1(this.multipleSelection[0].company_id,
                this.multipleSelection[0].company_pid,
                this.multipleSelection[0].index)
            }else{
                this.deleAll()
            }

        }
      },
      //判断当前账号是否属于该公司
      judge(id){
        this.axios.get('/api/v1/flow/currentcompanyjudge/'+`${id}`
        )
          .then((res)=>{
            if(res.data.code==0){
              console.log(res.data.data);
              this.self_identify =res.data.data.self_identify;
            }
          })
      },
      editor(company_id,company_pid,index){
        if(company_pid==0&&this.company_pids!=0){
          this.$alert('不允许直接操作顶级公司','提示')
          this.$refs.tableData3.clearSelection();
          return false;
        }
        else{
          if(company_pid==0&&this.company_pids==0){
              this.showTree =false;
          }else{
            this.showTree =true;
          }
          this.company_id=company_id;
          this.company_pid=company_pid;
          this.index=index;
          this.editorCompanyData(company_pid);
          this.initCompanyData(company_id);
          this.title='编辑公司';

        }
      },
      //表格内容区域删除操作
      delete1(company_id,company_pid,index){
          if(company_pid==0&&this.company_pids!=0){
            this.$alert('不允许直接操作顶级公司','提示')
            this.$refs.tableData3.clearSelection();
          }else{
            this.company_id=company_id
            this.company_pid=company_pid
            this.index=index
            this.dialogFormVisible2 =true
          }
      },
      deleAll(){
        var params=''
          for(var i in this.multipleSelection){
            params+=','+this.multipleSelection[i].company_id
          }
        this.axios.delete('/api/v1/system/company/'+`${params}`)
          .then((res)=>{
            this.$alert(res.data.message,'提示')
            console.log(this.multipleSelection)
            console.log(this.tableData3)
            if(res.data.code==0){
                //批量删除
                for(var k in this.multipleSelection){
                    for(var j in this.tableData3){
                        if(this.multipleSelection[k].company_id==this.tableData3[j].company_id){
                           this.tableData3.splice(j,1)
                        }
                    }
                }
            }else{
              this.$alert(res.data.message,'提示')
            }
          }).then((res)=>{
          this.$refs.tableData3.clearSelection();
        })
          .catch((err)=>{
          this.$alert(err.message,'提示')
          this.$refs.tableData3.clearSelection();
        })
        this.dialogFormVisible2 =false
      },
      //获取选定的数据
      editorCompanyData(id){
        this.axios.get('/api/v1/system/company/'+`${this.company_id}`)
          .then((res)=>{
            this.$refs.tableData3.clearSelection();
            if(res.data.code==0){
              this.dialogFormVisible =true;
              console.log(res.data.data.company_pid)
                this.form =res.data.data;
                if(res.data.data.company_sort){
                  this.company_sort =res.data.data.company_sort||'';
                }else{
                  this.company_sort =""
                }
                if(this.showTree){
                  if(this.$refs.tree){
                    this.$refs.tree.setCheckedKeys([res.data.data.company_pid]);
                  }
                }
            }else{
              this.$alert(res.data.message,'提示')
            }
          })
      },

//      确认编辑{添加公司}
      confirmEditor(formName){
        if(this.title=='添加公司'){
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.axios.post('/api/v1/system/company',
                {
                  company_pid:(this.$refs.tree.getCheckedNodes()[0]).company_id,
                  company_name:this.form.company_name,
                  company_num:this.form.company_num,
                  company_state:this.form.company_state,
                  company_sort:this.company_sort||1
                })
                .then((res)=>{
                  console.log(res.data)
                  this.dialogFormVisible=false
                  if(res.data.code==0){
                    this.form={};
                    this.$refs[formName].resetFields();
                    this.$refs.tree.setCheckedNodes([]);
                    this.initData();
                  }else{
                    this.form={};
                    this.$refs[formName].resetFields();
                    this.$refs.tree.setCheckedNodes([]);
                    this.$alert(res.data.message, '提示', {
                      confirmButtonText: '确定'
                    })
                  }
                })
            }else{
              console.log('error submit!!');
              return false;
            }
          })
//            this.editorNewCompany()
        }else if(this.title=='编辑公司'){
//          this.addNewCompany()
          this.$refs[formName].validate((valid) => {
            if (valid) {
                if(this.showTree){
                  this.axios.put('/api/v1/system/company/'+`${this.company_id}`,
                    {
                      company_pid:(this.$refs.tree.getCheckedNodes()[0]).company_id,
                      company_name:this.form.company_name,
                      company_num:this.form.company_num,
                      company_state:this.form.company_state,
                      company_id:this.company_id,
                      company_sort:this.company_sort||1
                    })
                    .then((res)=>{
                      console.log(res.data)
                      this.dialogFormVisible=false
                      if(res.data.code==0){
                        this.form={};
                        this.$refs[formName].resetFields();
                        this.$refs.tree.setCheckedNodes([]);
                        this.initData();
                        this.$refs.tableData3.clearSelection();
                      }else{
                        this.form={};
                        this.$refs[formName].resetFields();
                        this.$refs.tree.setCheckedNodes([]);
                        this.$refs.tableData3.clearSelection();
                        this.$alert(res.data.message, '提示', {
                          confirmButtonText: '确定'
                        })
                      }
                    })
                }else{
                  this.axios.put('/api/v1/system/company/'+`${this.company_id}`,
                    {
                      company_name:this.form.company_name,
                      company_num:this.form.company_num,
                      company_state:this.form.company_state,
                      company_id:this.company_id,
                      company_sort:this.company_sort||1
                    })
                    .then((res)=>{
                      console.log(res.data)
                      this.dialogFormVisible=false;
                      this.showTree =true;
                      if(res.data.code==0){
                        sessionStorage.setItem('company_name',this.form.company_name);
                        this.form={};
                        this.$refs[formName].resetFields();
                        this.initData();
                        this.$refs.tableData3.clearSelection();
                      }else{
                        this.$refs[formName].resetFields();
                        this.$refs.tree.setCheckedNodes([]);
                        this.$refs.tableData3.clearSelection();
                        this.$alert(res.data.message, '提示', {
                          confirmButtonText: '确定'
                        })
                      }
                    })
                }

            }else{
              console.log('error submit!!');
              return false;
            }
          })
        }
      },
//      取消编辑添加公司  数据清空
      cancelEditor(){
          this.form={}
          this.title='';
          if(this.showTree){
            this.$refs.tree.setCheckedKeys([]);
          };
          this.dialogFormVisible=false;
      },
//取消删除操作
      cancelOpt(){
        console.log(456)
        this.dialogFormVisible2 =false
      },
 //确认删除公司
      confirmOpt(){
        if(this.company_pid==0&&this.company_pids!=0){
          //不允许直接删除顶级公司
          this.$alert('不允许直接删除顶级公司', '提示', {
            confirmButtonText: '确定'
          });
        }else{
          this.axios.delete('/api/v1/system/company/'+`${this.company_id}`)
            .then((res)=>{
              this.$alert(res.data.message,'提示')
              this.$refs.tableData3.clearSelection();
              if(res.data.code==0){
                this.tableData3.splice(this.index,1)
                this.company_id=''
                this.company_pid=''
                this.index=''
              }
            })
        }
        this.dialogFormVisible2 =false
      },

      renderHeaderOne (h, {column, $index}) {
        return h('span', [
          h('span', column.label),
          h('span', {
            class: 'addIcon',
            on: {
              click: () => {
                console.log(`${column.label}   ${$index}`)
              }
            }
          })
        ])
      },
      initData(){
          this.axios.get('/api/v1/system/company').then((res)=>{
              console.log(res.data)
              if(res.data.code==0){
                this.tableData3=res.data.data
                let tmp;
                if (!Array.isArray(res.data.data)) {
                  tmp = [res.data.data]
                } else {
                  tmp = res.data.data
                }
                const func = this.evalFunc || treeToArray
                const args = this.evalArgs ? Array.concat([tmp, this.expandAll], this.evalArgs) : [tmp, this.expandAll]
                console.log(args);
                console.log(func.apply(null, args));
                this.tableData3 =func.apply(null, args);
                console.log(this.tableData3)
              }
          })
      },
      //初始化树状结构的公司列表
      initCompanyData(id){
        //        this.axios.get('api/v1/system/comcontain/'+`${id}`).then((res)=>{
        this.axios.get('/api/v1/system/comsection').then((res)=>{
          console.log(res.data)
          if(res.data.code==0){
            this.loading=false
            this.data3=res.data.data
          }else{
              //异常处理
          }
        })
      },
      initCompanyData2(){
          if(!sessionStorage.getItem('company_pid')){
            this.axios.get('/api/v1/system/comsection').then((res)=>{
              if(res.data.code==0){
                this.loading=false
                this.data3=res.data.data
              }else{
                //异常处理
              }
            })
          }else{
            this.axios.get('/api/v1/system/comsection?subor=collar').then((res)=>{
              if(res.data.code==0){
                this.loading=false
                this.data3=res.data.data
              }else{
                //异常处理
              }
            })
          }

      }
    },
    mounted(){
        this.initData();
//        this.judge(this.company_ids)
    }
  })
</script>
<style scoped="">
  .companyManaIndex{
    width: 100%;
    height: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding: 10px;
  }
  .companyManaIndex .el-table{
    margin-bottom: 30px;
  }
  .companyManaIndex .el-table  >>>  th.is-leaf{
    background: #d3e9bb;
    height:58px;

  }
  .companyManaIndex .el-table  >>> thead   .cell{
    font-size: 14px;
    color: #5d9120;
    font-weight: normal;
  }
  .companyManaIndex .el-table  >>> tr  th.is-leaf{
    border-bottom: 1px solid #aac983;
    border-right: 1px solid #aac983;
  }
  .companyManaIndex .el-table  >>> .el-table__body-wrapper{
  }
  .companyManaIndex  .el-table  >>> .el-table__body-wrapper  .el-table__body  .el-table__row{
    height: 50px !important;
  }
  .companyManaIndex  .el-table >>> .el-table__body-wrapper   .el-table__body  .el-table__row td{
    height: 50px;
    /*border-bottom: 1px solid #aac983;*/
    border-right: 1px solid #aac983;
  }
  .companyManaIndex  .el-table >>> .el-table__body-wrapper   .el-table__body  .el-table__row td.e-table-align-left .cell {
    text-align: left;
    padding-left: 6px;
    padding-right: 0;
  }
  .companyManaIndex .el-table >>> .el-table__body-wrapper   .el-table__body tr{
    border-bottom: 1px solid #aac983;
  }
  .companyManaIndex .el-table  >>> .el-table__body-wrapper  .el-table__body  .el-table__row .cell{
    text-align: center;
    position: relative;
  }
  .companyManaIndex .el-table  >>> .el-table__body-wrapper  .el-table__body  .el-table__row .cell img{
    display: inline-block;
    /*position: absolute;*/


  }
  .companyManaIndex .el-table >>>  span{
    position: relative;
  }
  .companyManaIndex .el-table >>>  span img{
    /*position: absolute;*/
    /*left: 0;*/
    /*top:50%;*/
    /*-webkit-transform: translate();*/
    /*-moz-transform: translate();*/
    /*-ms-transform: translate();*/
    /*-o-transform: translate();*/
    /*transform: translate();*/
  }
  .companyManaIndex .el-table  >>>  .el-table__header .has-gutter th{
    text-align: center;
    background: #d3e9bb;
  }
  .companyManaIndex  .el-table  >>>  .el-table__header .has-gutter th .el-checkbox{
    display: none;
  }
  .companyManaIndex .el-table >>>  span.e-ditor{
    margin-right:24px ;
    color: #4577bf;
    text-decoration: underline;
  }
  .companyManaIndex  .el-table >>>  span.d-elete{
    color: #4577bf;
    text-decoration: underline;
  }
  .companyManaIndex >>> .el-form-item__content{
    width: 380px;
  }
  .companyManaIndex >>> .el-tree__empty-block{
    min-height: 40px;
  }
  .companyManaIndex >>>  .el-dialog .el-form .el-form-item{
    margin-bottom: 24px;
  }
  @media screen and (max-width: 1400px){
    .companyManaIndex{
      padding: 6px;
    }
  }
</style>
